import {OnDestroy, ViewChild} from '@angular/core';
import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';
import {Subscription} from "rxjs";
import {MineService} from "@mine/mine.service";
import {AuthService} from "@shared/service/auth/auth.service";
import {ToolsService} from "@shared/service/tools/tools.service";
import {ToolbarService} from "@shared/components/toolbar/toolbar.service";


@Component({
  selector: 'my-content',
  templateUrl: './edit-detail.html',
  styleUrls: ['./edit-detail.scss'],
  encapsulation: ViewEncapsulation.None
})

export class EditDetailComponent implements OnInit, OnDestroy {
  public infotype: string;
  public title: string;
  public newinfo: string;
  public subscription: Subscription = new Subscription();


  @ViewChild('info') userName;

  constructor(public mineService: MineService,
              public activatedroute: ActivatedRoute,
              public router: Router,
              public toolservice: ToolsService,
              public authservice: AuthService,
              public toolBarService: ToolbarService
  ) {

  }

  saveinfo(value) {
    if (value && value === this.newinfo) {
      this.router.navigate(['./mine/setting/profile']);
    } else {
      if (!value || value === '') {
        this.toolservice.showToast('内容不能为空');
        return;
      }

      if (value.length < 4 || value.length > 20) {
        this.toolservice.showToast('内容长度只能在4-20个字符之间');
        return;
      }

      const str = '{"' + this.infotype + '":"' + value + '"}';
      const data = JSON.parse(str);
      this.toolservice.showLoading();
      this.subscription.add(
        this.mineService.UserInfoUpdate(data).subscribe(res => {
          this.toolservice.hideLoading();
          if (res.result === '0') {
            this.router.navigate(['./mine/setting/profile']);
          } else {
            this.toolservice.showToast(res.msg);
          }
          // res.result === '0' ? this.router.navigate(['./mine/setting']) : this.toolservice.showToast(res.msg);
        })
      );
    }
  }

  ngOnInit() {
    this.activatedroute.queryParams.do(() => this.toolBarService.unfoldNav()).subscribe(param => {
      const infolist = ['编辑昵称', '编辑签名'];
      param.type === 'sign' ? this.title = infolist[1] : this.title = infolist[0];
      this.infotype = param.type;
      if (param.placeHolder) {
        this.userName.nativeElement.value = this.newinfo = param.placeHolder;
      }
      // param.placeHolder ? this.userName.nativeElement.value = this.newinfo = param.placeHolder : '';
    });
  }

  ngOnDestroy() {
    // 取消订阅
    this.subscription.unsubscribe();
    this.toolservice.hideLoading();
  }
}
